// add this file to the module.js
angular.module('wechat').controller('configIndexCtrl', ['$scope', 'Pagination', 'wechatService', function ($scope, Pagination, wechatService) {

    var pagination = $scope.pagination = Pagination.create({
        itemsPerPage: window.user.perPage,
        maxNumbers: 5,
        itemsCount: 0
    });

    pagination.onChange = function (page) {
        onLoadData({page: page});
    };
    $scope.datas = [];

    function onLoadData(params) {
        var searchParams = _.assign({
            'page': 0,
            'perPage': pagination.itemsPerPage
        }, params);

        wechatService.configList(searchParams).then(function (response) {
            pagination.itemsCount = response.total;
            $scope.datas = response.result;
        }, function (error) {
            layui.use('layer', function () {
                layer.alert(error, {icon: 2}, function (index) {
                    layer.close(index);
                });
            });
        })
    }

    onLoadData();

    $scope.toEdit = function (x, index) {
        if (x == 0) {
            xlayer.open('添加公众号', '?r=wechat/config/edit', function (data) {
                $scope.datas.push(data);
                pagination.itemsCount++;
                $scope.$apply();
            });
        } else {
            xlayer.open('修改公众号', '?r=wechat/config/edit&id=' + x.id, function (data) {
                $scope.datas[index] = _.assign(x, data);
                $scope.$apply();
            });
        }
    };

    $scope.toDelete = function (x, oindex) {
        var num = parseInt(Math.random() * 100);
        danger_prompt({
            text: '你确定要删除此公众号吗!!<br/>如果你仍然确定删除，请输入:' + num
        }, function (value, index, elem) {
            if (num === parseInt(value)) {
                $.post("?r=wechat/config/delete&id=" + x.id, _.assign({
                    _csrf: $('#_csrf').val()
                }), function () {
                    $scope.datas.splice(oindex, 1);
                    pagination.itemsCount--;
                    $scope.$apply();
                }, 'text');
                layer.close(index);
            } else {
                layer.msg('填写错误,删除失败', {icon: 2, time: 1000});
            }
        });
    };
    // 显示信息
    $scope.showConfig = function (x) {
        openInLayer('wechat/config/index&api=show&id=' + x.id, '查看配置')
    };
    // 切换状态
    $scope.toggleAttr = function (attr, x) {
        var text = attr + '_text';
        $.post("?r=wechat/config/index&api=changeattrs", {
            id: x.id,
            attr: attr,
            _csrf: $('#_csrf').val()
        }, function (result) {
            x[attr] = result[attr];
            x[text] = result[text];
            $scope.$apply();
        }, 'json');
    };
}]);